import { Pressable, StatusBar, StyleSheet, Text, View, Image, ScrollView } from 'react-native';
import React, { useState, useEffect, useRef } from 'react';
import Icon from 'react-native-vector-icons/Ionicons';
import LinearGradient from 'react-native-linear-gradient';
import { useTranslation } from 'react-i18next';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useNavigation, useRoute } from '@react-navigation/native';
import { deviceStore, observer, webSocketStore } from '~/store';
import { onePx, px2dp, scale } from '~/utils/px2dp';
import { setLaserParams, openLaser } from '~/utils/ble/application';
import { TransitionModal, MyLoading } from '~/components';
import { useTimeout } from '~/common';

const OpenLaser = observer(() => {
    const insets = useSafeAreaInsets();
    const { t } = useTranslation();
    const router = useRoute<any>();
    const loadingRef = useRef<any>();
    const [isTimeout, startTimer, resetTimer] = useTimeout(10); // 获取超时相关
    const { type, device_sn, subDevice_sn, device_code, power = '4', duration = '24' } = router.params || {};
    const navigation: any = useNavigation();
    const powerData = [1, 2, 3, 4];
    const durationData = [8, 16, 24, 32];
    const [visible, setVisible] = useState(false);
    const { laserStatus, laserParamsResult, isOpenStatus } = deviceStore.laser;
    const { linkSubDeviceStatus } = webSocketStore;
    const [selectPower, setSelectPower] = useState(power);
    const selectMenuPower = (row) => {
        setSelectPower(row);
    };
    const [selectDuration, setSelectDuration] = useState(duration);
    const selectMenuDuration = (row) => {
        setSelectDuration(row);
    };
    useEffect(() => {
        resetTimer();
        loadingRef.current.hideLoading();
    }, [laserStatus]);
    const onPress = () => {
        if (linkSubDeviceStatus == 0 && deviceStore.device.connectedDeviceStatus == 0) {
            Toast.show({ content: t('OpenLaser.t17') });
            return;
        }
        startTimer();
        loadingRef.current.showLoading();
        if (deviceStore.laser.isOpenStatus) {
            openLaser(0, router.params);
        } else {
            setLaserParams(selectPower, selectDuration, router.params); // 设置手动激光参数
            setTimeout(() => {
                openLaser(1, router.params);
                loadingRef.current.hideLoading();
            }, 300);
        }
    };
    // useEffect(() => {
    //     if (laserParamsResult == 0) {
    //         setTimeout(() => {
    //             openLaser(1, router.params);
    //             loadingRef.current.hideLoading();
    //         }, 500);
    //     }
    // }, [laserParamsResult]);

    useEffect(() => {
        if (isTimeout) {
            Toast.show({ content: t('OpenLaser.t18') });
            loadingRef.current.hideLoading();
            resetTimer();
            Object.assign(deviceStore.laser, {
                laserStatus: -1,
                laserParamsResult: -1,
                isOpenStatus: false,
            });
        }
    }, [isTimeout]);

    return (
        <LinearGradient colors={['#F3FCFF', '#DBF9FB']} style={styles.container}>
            <StatusBar translucent={true} backgroundColor={'#F3FCFF'} />
            <View style={[styles.row, styles.between, { marginLeft: px2dp(32), marginTop: insets.top }]}>
                <Pressable onPress={() => navigation.goBack()}>
                    <Icon name="chevron-back-outline" size={26} color={'#000'}></Icon>
                </Pressable>
                <Text style={styles.title}>{t('OpenLaser.title')}</Text>
                <View />
            </View>
            <ScrollView contentContainerStyle={styles.contentContainerStyle} showsVerticalScrollIndicator={false}>
                <View style={styles.cover_container}>
                    <Image
                        source={{
                            uri: 'https://bjy-dev.oss-cn-shenzhen.aliyuncs.com/xcx/img/01Cjiguangkaiqizhuangtai.png?1',
                        }}
                        style={styles.cover}
                    />
                </View>
                <View style={styles.menue}>
                    <View>
                        <View style={styles.row}>
                            <Text style={styles.menueTitle}>{t('OpenLaser.t1')}</Text>
                            <Pressable onPress={() => setVisible(true)}>
                                <Image style={styles.issue} source={require('~/assets/user/issue.png')} />
                            </Pressable>
                        </View>

                        <View style={[styles.row, styles.between]}>
                            {powerData.map((item, index) => {
                                return (
                                    <Pressable
                                        key={index}
                                        style={[styles.list, selectPower == item && { backgroundColor: '#1877FF' }]}
                                        onPress={() => selectMenuPower(item)}>
                                        <Text style={selectPower == item && { color: '#fff' }}>
                                            {item == 4 ? t('OpenLaser.t2') : item + t('OpenLaser.t3')}
                                        </Text>
                                    </Pressable>
                                );
                            })}
                        </View>
                    </View>
                    <View style={{ marginTop: px2dp(64) }}>
                        <View style={styles.row}>
                            <Text style={styles.menueTitle}>{t('OpenLaser.t4')}</Text>
                            <Pressable onPress={() => setVisible(true)}>
                                <Image style={styles.issue} source={require('~/assets/user/issue.png')} />
                            </Pressable>
                        </View>
                        <View style={[styles.row, styles.between]}>
                            {durationData.map((item, index) => {
                                return (
                                    <Pressable
                                        key={index}
                                        style={[styles.list, selectDuration == item && { backgroundColor: '#1877FF' }]}
                                        onPress={() => selectMenuDuration(item)}>
                                        <Text style={selectDuration == item && { color: '#fff' }}>
                                            {item}
                                            {t('OpenLaser.t5')}
                                        </Text>
                                    </Pressable>
                                );
                            })}
                        </View>
                    </View>
                    <Pressable style={styles.btn} onPress={onPress}>
                        <Image
                            style={styles.icons}
                            source={{
                                uri: isOpenStatus
                                    ? 'https://bjy-dev.oss-cn-shenzhen.aliyuncs.com/xcx/images/openBtn.png'
                                    : 'https://bjy-dev.oss-cn-shenzhen.aliyuncs.com/xcx/images/closeBtn.png',
                            }}
                        />
                        <Text>{isOpenStatus ? t('OpenLaser.t6') : t('OpenLaser.t7')}</Text>
                    </Pressable>
                </View>
            </ScrollView>
            <TransitionModal visible={visible} toggleVisible={() => setVisible(false)}>
                <View>
                    <Text style={styles.t1}>{t('OpenLaser.t8')}</Text>
                    <Text style={styles.t2}>{t('OpenLaser.t9')}</Text>
                    <Text style={styles.t2}>{t('OpenLaser.t10')}</Text>
                    <Text style={styles.t2}>{t('OpenLaser.t11')}</Text>
                    <Text style={styles.t2}>{t('OpenLaser.t12')}</Text>
                    <Text style={styles.t1}>{t('OpenLaser.t13')}</Text>
                    <Text style={styles.t2}>{t('OpenLaser.t14')}</Text>
                </View>
            </TransitionModal>
            <MyLoading ref={loadingRef} title={isOpenStatus ? t('OpenLaser.t15') : t('OpenLaser.t16')} />
        </LinearGradient>
    );
});
export default OpenLaser;
const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    container: {
        flex: 1,
    },
    title: {
        fontSize: scale(28),
        color: '#000',
        fontWeight: 'bold',
    },
    cover_container: {
        flexGrow: 1,
        alignItems: 'center',
        marginTop: '30%',
    },
    cover: {
        resizeMode: 'contain',
        width: px2dp(500),
        height: px2dp(500),
    },
    menue: {
        flexGrow: 1,
        backgroundColor: '#fff',
        padding: px2dp(24),
        paddingTop: px2dp(64),
    },
    menueTitle: {
        fontSize: scale(28),
        color: '#000',
        fontWeight: 'bold',
        marginBottom: px2dp(24),
    },
    list: {
        borderWidth: onePx,
        borderColor: '#191919',
        width: px2dp(120),
        height: px2dp(60),
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: px2dp(12),
    },
    contentContainerStyle: {
        flexGrow: 1,
    },
    icons: {
        width: px2dp(80),
        height: px2dp(80),
    },
    btn: {
        justifyContent: 'center',
        alignItems: 'center',
        marginTop: px2dp(80),
    },
    issue: {
        width: px2dp(38),
        height: px2dp(38),
        marginLeft: px2dp(4),
        marginBottom: px2dp(24),
    },
    t1: {
        color: '#000',
        fontSize: scale(28),
        fontWeight: 'bold',
        marginTop: px2dp(32),
    },
    t2: {
        marginTop: px2dp(12),
        fontSize: scale(24),
        color: '#a4a4a4',
    },
});
